<template>
	<div class="login_container">
		<el-form ref="form" :rules="rules" :model="form">
			<!-- 这是填写用户名的表单 -->
			<UserName :userName="form.userName" />
			<!-- 这是填写密码的表单 -->
			<Password :password="form.password" />
		</el-form>

		<el-row class="login_button">
			<el-button type="primary" plain @click="verification">登录</el-button>

			<el-button type="info" plain @click="reset">重置</el-button>
		</el-row>
	</div>
</template>
<script>
import UserName from './UserName.vue'
import Password from './Password.vue'

export default {
	name: 'LoginFromInput',
	components: {
		UserName,
		Password,
	},
	data() {
		return {
			form: {
				userName: 'admin',
				password: '123456',
			},
			rules: {
				userName: [
					{ required: true, message: '用户名不能为空', trigger: 'blur' },
				],
				password: [
					{ required: true, message: '密码不能为空', trigger: 'blur' },
					{ min: 6, message: '密码长度不少于6', trigger: 'blur' },
				],
			},
		}
	},
	methods: {
		reset() {
			this.$refs.form.resetFields()
		},
		verification() {
			this.$refs.form.validate(data => {
				if (data) {
					this.$http
						.post('/login', {
							username: this.form.userName,
							password: this.form.password,
						})
						.then(response => {
							const { data, meta } = response.data
							if (meta.status !== 200) {
								this.$message.error(meta.msg)
								return
							}
							this.$message({
								message: '登录成功！',
								type: 'success',
							})
							sessionStorage.setItem('token', data.token)
							this.$router.push({
								name: 'home',
							})
						})
						.catch(error => {
							console.log(error.message)
						})
				}
			})
		},
	},
	mounted() {
		this.$bus.$on('userName', data => {
			this.form.userName = data
		})
		this.$bus.$on('password', data => {
			this.form.password = data
		})
	},
}
</script>

<style scoped>
.login_container {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 100%;
}
.login_button {
	display: flex;
	justify-content: space-around;
}

.el-input {
	width: 100%;

	box-sizing: border-box;
}
.login_input {
	box-sizing: border-box;
	padding: 0 20px;
}
</style>
